package com.wufun.baselibrary.download;

import android.content.Context;
import android.util.Log;

import org.greenrobot.eventbus.EventBus;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;

/**
 * 扫描连接wifi 热点的数量
 * Created by tangbl on 2017/12/6 0006.
 */

public class ScanApClientThread implements Runnable {
    private static final String TAG = ScanApClientThread.class.getSimpleName();
    private Context mContext;
    boolean mOnlyReachable = false;
    List<ClientScanEvent> clients = null;
    long mTime;
    boolean mointor = true;


    public ScanApClientThread(Context mContext, boolean onlyReachable, long timeInterval) {
        this.mContext = mContext;
        this.mOnlyReachable = onlyReachable;
        clients = new ArrayList<ClientScanEvent>();
        mTime = timeInterval;
        Log.d(TAG, "ScanApClientThread: mTime::" + mTime);
    }

    @Override
    public void run() {
        while (mointor) {
            try {
                clients = getArpLiveIps(mOnlyReachable);
                Log.d(TAG, "run: 数量" + clients.size());
                EventBus.getDefault().post(clients);
                Thread.sleep(mTime);
            } catch (InterruptedException e) {
                Thread.interrupted();
                e.printStackTrace();
            }
        }

    }


    /**
     * Gets a list of all clients Ip Addresses connected to the Hotspot from ARP file
     *
     * @param onlyReachables false if the list should contain unreachable clients or true otherwise
     * @return ArrayList of all clients Ip Addresses
     */
    public ArrayList<ClientScanEvent> getArpLiveIps(boolean onlyReachables) {
        BufferedReader bufRead = null;
        ArrayList<ClientScanEvent> result = null;
        try {
            result = new ArrayList<ClientScanEvent>();
            bufRead = new BufferedReader(new FileReader("/proc/net/arp"));
            String fileLine;
            boolean isReachable = false;
            while ((fileLine = bufRead.readLine()) != null) {
                String[] splitted = fileLine.split(" +");
                if ((splitted != null) && (splitted.length >= 4)) {

                    String mac = splitted[3];
                    String ip = splitted[0];
                    if (mac.matches("..:..:..:..:..:..")) {
                        isReachable = pingCmd(splitted[0]);//有些机型这方法不适用
                        if (!isReachable) {
                            isReachable = InetAddress.getByName(splitted[0]).isReachable(3000);
                        }
                        if (!onlyReachables || isReachable) {
                            ClientScanEvent event = new ClientScanEvent(isReachable, mac, ip);
                            result.add(event);
                        }
                    }
                }
            }
        } catch (Exception e) {

        } finally {
            try {
                bufRead.close();
            } catch (IOException e) {

            }
        }
        return result;
    }


    /**
     * Method to Ping  IP Address
     *
     * @param addr IP address you want to ping it
     * @return true if the IP address is reachable
     */
    public boolean pingCmd(String addr) {
        try {
            String ping = "ping  -c 1 -W 1 " + addr;
            Runtime run = Runtime.getRuntime();
            Process pro = run.exec(ping);
            try {
                pro.waitFor();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            int exit = pro.exitValue();
            //ip address is not reachable
            return exit == 0;
        } catch (IOException e) {
        }
        return false;
    }

    public void setMonitor(boolean b) {
        this.mointor = b;
    }

    void noClientConnected() {
        ClientScanEvent event = new ClientScanEvent();
        event.setReabchable(false);
        EventBus.getDefault().post(event);
    }
}

